package one.bugu.android.demon.ui.activity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.common.util.DeviceUtil;
import com.juefeng.android.framework.common.util.PermissionManager;
import com.juefeng.android.framework.common.util.ToastUtils;
import com.juefeng.android.framework.view.annotation.LKContentView;
import com.juefeng.android.framework.view.annotation.LKInjectView;

import one.bugu.android.demon.MyApplication;
import one.bugu.android.demon.R;

import one.bugu.android.demon.bean.GetCapCodeBean;
import one.bugu.android.demon.bean.LoginBean;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseActivity;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.util.ImgHelper;
import one.bugu.android.demon.util.IntentUtils;
import one.bugu.android.demon.util.ParamUtils;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.StatusBarUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 登录界面
 */
@LKContentView(R.layout.activity_tel_login)
public class TelLoginActivity extends MyBaseActivity {

    /**
     * 手机号编辑框
     */
    @LKInjectView(R.id.edt_tel)
    private EditText tel;

    /**
     * 父容器布局
     */
    @LKInjectView(R.id.ll_main_layout)
    private LinearLayout mMainLayout;

    /**
     * 验证码编辑框
     */
    @LKInjectView(R.id.edt_verificationCode)
    private EditText edtVerificationCode;

    /**
     * 协议文字
     */
    @LKInjectView(R.id.txt_agreement)
    private TextView protocolText;

    /**
     * 登录按钮
     */
    @LKInjectView(R.id.login_btn)
    private Button btnLogin;

    /**
     * 获取验证码按钮
     */
    @LKInjectView(R.id.get_verificationCode)
    private Button btnGetVerificationCode;

    /**
     * 协议外圈图
     */
    @LKInjectView(R.id.agreementW)
    private LinearLayout agreementW;

    /**
     * 协议内圈图
     */
    @LKInjectView(R.id.agreementN)
    private ImageView agreementN;

    /**
     * 图片验证码输入框
     */
    @LKInjectView(R.id.et_cap_code)
    private EditText etCapCode;

    /**
     * 图片验证码
     */
    @LKInjectView(R.id.iv_cap_code)
    private ImageView ivCapCode;

    /**
     * 图片验证码刷新按钮
     */

    @LKInjectView(R.id.iv_cap_code_refrush)
    private ImageView ivCapCodeBtn;
    /**
     * 手机号格式验证
     */
    String MATCH_PHONE_REGEX = "((13)|(14)|(15)|(17)|(18)|(19)|(16))\\d{9}$";

    /**
     * 图片验证码默认图
     */
    private int DEFAULT_CAP_CODE = -1;

    /**
     * 图片验证码数据
     */
    private GetCapCodeBean capCodeData;

    /**
     * 点击获取验证码进入倒计时 60秒
     */
    private CountDownTimer mCountDownTimer = new CountDownTimer(60000, 1000) {
        @SuppressLint("SetTextI18n")
        @Override
        public void onTick(long l) {
            //显示倒计时
            btnGetVerificationCode.setText((l / 1000) + "秒后可重发");
        }

        @Override
        public void onFinish() {
            btnGetVerificationCode.setEnabled(true);
            btnGetVerificationCode.setText("获取验证码");
            btnGetVerificationCode.setTextColor(Color.parseColor("#ff5965b0"));
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void initView() {
        super.initView();
        //设置沉浸式状态栏
        StatusBarUtils.getInstance().setStatusBar(this, mMainLayout);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            PermissionManager.checkFilePermission(this);
            PermissionManager.checkPermisstion(this, new String[]{"android.permission.READ_PHONE_STATE"}, 1);
        }
    }

    @Override
    public void permisssionsResultListener(int requestCode) {

    }


    /**
     * 登录
     */
    public void login() {
        String deviceToken = PreferencesUtil.getInstance().getString(getApplicationContext(), "deviceToken");
        //deviceToken 为空时,使用设备ID, 并使用UUID_进行标识
        if (TextUtils.isEmpty(deviceToken)) {
            deviceToken = "UUID_" + DeviceUtil.getDeviceId(this);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userName", tel.getText().toString());
        map.put("mobileCaptcha", edtVerificationCode.getText().toString());
        map.put("regFrom", "50");
        map.put("ymDeviceId", deviceToken);
        map.put("captcha", etCapCode.getText().toString().trim());
        map.put("timeFlag", capCodeData.getTime());
        LKUtil.getHttpManager().postBody(HttpConstant.LOGIN_URL, map, hanlder);
    }

    /**
     * 登录网络请求
     */
    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<LoginBean> hanlder = new BaseHttpAsycResponceHandler<LoginBean>(true) {
        @Override
        public void onSuccess(LoginBean loginBean) {
            super.onSuccess(loginBean);
            //结束首页MainActivity
            MyApplication.finishAllActivity();
            //用户昵称
            boolean nameFlag = loginBean.getNickname() != null && !TextUtils.isEmpty(loginBean.getNickname());
            String name = nameFlag ? loginBean.getNickname() : "";
            //保存客服昵称
            PreferencesUtil.getInstance().putString(TelLoginActivity.this, Constant.WECHAT_ACCOUNT, loginBean.getWechatAccount());
            PreferencesUtil.getInstance().putInt(TelLoginActivity.this, Constant.USER_ID, loginBean.getRowId());
            //保存昵称
            PreferencesUtil.getInstance().putString(TelLoginActivity.this, Constant.USER_NAMR, name);
            //保存头像
            PreferencesUtil.getInstance().putString(TelLoginActivity.this, Constant.USER_AVATAR, loginBean.getPhoto());
            //登录成功后, 存储token, 以后要用到
            PreferencesUtil.getInstance().putString(TelLoginActivity.this, Constant.TOKEN, loginBean.getToken());
            //登录成功后, 存储邀请码
            PreferencesUtil.getInstance().putString(TelLoginActivity.this, Constant.INVITE_CODE, loginBean.getInviteCode());
            //新老用户标识
            String flag = PreferencesUtil.getInstance().getString(TelLoginActivity.this, Constant.FLAG);
            //老用户, 直接跳转预警主界面
            if (loginBean.getReadyReg() == null) {
                //记录为登录状态
                PreferencesUtil.getInstance().putBoolean(TelLoginActivity.this, Constant.IS_LOGIN, true);
                Toast.makeText(TelLoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                //新老用户标识, 0位老用户
                PreferencesUtil.getInstance().putString(TelLoginActivity.this, Constant.FLAG, "0");
                IntentUtils.startAty(TelLoginActivity.this, WarnMainActivity.class);
                finish();
            } else {
                //新用户
                if ("0".equals(loginBean.getReadyReg())) {
                    //新用户, 跳转引导页面
                    IntentUtils.startAty(TelLoginActivity.this, InviteActivity.class);
                    //记录为登录状态
                    PreferencesUtil.getInstance().putBoolean(TelLoginActivity.this, Constant.IS_LOGIN, true);
                    Toast.makeText(TelLoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    PreferencesUtil.getInstance().putString(TelLoginActivity.this, Constant.FLAG, "1");
                    PreferencesUtil.getInstance().putInt(TelLoginActivity.this, Constant.RANKING_NUM, loginBean.getRanking());
                    PreferencesUtil.getInstance().putInt(TelLoginActivity.this, Constant.DRAW_BGT_NUM, loginBean.getDrawBgtNum());
                    finish();
                } else {
                    //记录为登录状态
                    PreferencesUtil.getInstance().putBoolean(TelLoginActivity.this, Constant.IS_LOGIN, true);
                    Toast.makeText(TelLoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    //新老用户标识, 0位老用户
                    PreferencesUtil.getInstance().putString(TelLoginActivity.this, Constant.FLAG, "1");
                    IntentUtils.startAty(TelLoginActivity.this, WarnMainActivity.class);
                    finish();
                }
            }

        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
            ToastUtils.custom(message);
        }

        @Override
        public void onError() {
            super.onError();
        }
    };

    /**
     * 检测新老用户
     */
    public void checkUser() {
        Map<String, String> map = new HashMap<>();
        map.put("phone", tel.getText().toString());

        LKUtil.getHttpManager().postBody(HttpConstant.CHECKEDUSER_URL, map, checkUserHandler);
    }

    /**
     * 检测新老用户网络请求
     */
    @Override
    protected void initData() {
        super.initData();

        //获取图片验证码
        getCapCode();
    }

    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<String> checkUserHandler = new BaseHttpAsycResponceHandler<String>(true) {

        @Override
        public void onSuccess(String data) {
            super.onSuccess(data);
            //新老用户标识, 0位老用户
            PreferencesUtil.getInstance().putString(TelLoginActivity.this, Constant.FLAG, "0");
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
            if (code == -1) {
                //返回code == -1, 表示新用户, flag设为1
                PreferencesUtil.getInstance().putString(TelLoginActivity.this, Constant.FLAG, "1");
            } else {
                PreferencesUtil.getInstance().putString(TelLoginActivity.this, Constant.FLAG, "0");
            }
        }

        @Override
        public void onError() {
            super.onError();
        }
    };

    @Override
    protected void initEvent() {
        super.initEvent();
        //协议点击事件, 跳转协议详细信息页面 为h5页面
        protocolText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<ParamUtils.NameValue> parList = ParamUtils.build().put(WebActivity.TITLE, "用户协议").put(WebActivity.URL, HttpConstant.PROTOCOL_URL).create();
                IntentUtils.startAty(TelLoginActivity.this, WebActivity.class, parList);
            }
        });

        //获取验证码点击事件
        btnGetVerificationCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String capCode = etCapCode.getText().toString().trim();
                if (TextUtils.isEmpty(capCode)) {
                    Toast.makeText(TelLoginActivity.this, "请输入图片验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                //验证手机号格式
                Pattern p = Pattern.compile(MATCH_PHONE_REGEX);
                final Matcher m = p.matcher(tel.getText().toString());
                //格式正确调用验证新老用户和获取验证码方法
                if (m.matches()) {
                    if (capCodeData != null) {
                        getVerificationCodeFuction();
                    } else {
                        ToastUtils.custom("验证码错误");
                    }
                    // checkUser();
                } else {
                    Toast.makeText(TelLoginActivity.this, "请输入正确手机号", Toast.LENGTH_SHORT).show();
                }


            }
        });

        //登录
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //验证码为4位
                if (edtVerificationCode.getText().toString().length() < 4) {
                    ToastUtils.custom("验证码输入不合法");
                    return;
                }
                //图片验证码
                if (TextUtils.isEmpty(etCapCode.getText().toString().trim())) {
                    ToastUtils.custom("请输入图片验证码");
                    return;
                }
                //验证手机号格式
                Pattern p = Pattern.compile(MATCH_PHONE_REGEX);
                final Matcher m = p.matcher(tel.getText().toString());
                //格式正确 调用登录方法
                if (m.matches()) {
                    if (capCodeData != null) {
                        login();
                    } else {
                        ToastUtils.custom("验证码错误");
                    }
                } else {
                    Toast.makeText(TelLoginActivity.this, "请输入有效的手机号!", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //手机号编辑框监听事件
        tel.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                //手机号为空 获取验证码不可点击
                if (tel.length() != 0 && btnGetVerificationCode.getText().toString().equals("获取验证码")) {
                    btnGetVerificationCode.setEnabled(true);
                    btnGetVerificationCode.setTextColor(Color.parseColor("#ff5965b0"));
                } else {
                    btnGetVerificationCode.setEnabled(false);
                    btnGetVerificationCode.setTextColor(Color.parseColor("#A9A9A9"));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        //验证码输入框监听事件
        edtVerificationCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @SuppressLint("NewApi")
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //验证码不为空并且同意协议已勾选 登录按钮方可点击
                if (edtVerificationCode.length() != 0 && agreementN.getVisibility() == View.VISIBLE) {
                    btnLogin.setBackgroundResource(R.mipmap.denglu);
                    btnLogin.setEnabled(true);
                } else {
                    btnLogin.setBackgroundResource(R.mipmap.denglu3);
                    btnLogin.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        //协议圈点击事件
        agreementW.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (agreementN.getVisibility() == View.GONE) {
                    agreementN.setVisibility(View.VISIBLE);
                } else if (agreementN.getVisibility() == View.VISIBLE) {
                    agreementN.setVisibility(View.GONE);
                }
                if (agreementN.getVisibility() == View.VISIBLE && tel.length() != 0 && edtVerificationCode.length() != 0) {
                    btnLogin.setBackgroundResource(R.mipmap.denglu);
                    btnLogin.setEnabled(true);
                } else {
                    btnLogin.setBackgroundResource(R.mipmap.denglu3);
                    btnLogin.setEnabled(false);
                }
            }
        });
        //图片验证码刷新按钮点击事件处理
        ivCapCodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCapCode();
            }
        });

    }

    /**
     * 获取验证码
     */
    public void getVerificationCodeFuction() {
        Map<String, String> map = new HashMap<>();
        map.put("userPhone", tel.getText().toString());
        map.put("modelType", "100");
        map.put("captcha", etCapCode.getText().toString().trim());
        map.put("timeFlag", capCodeData.getTime());
        LKUtil.getHttpManager().postBody(HttpConstant.GETYZM_URL, map, getVerificationCodeHanlder);
    }

    /**
     * 获取验证码网络请求
     */
    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<String> getVerificationCodeHanlder = new BaseHttpAsycResponceHandler<String>(true) {

        @Override
        public void onSuccess(String data) {
            super.onSuccess(data);
            //开始倒计时
            mCountDownTimer.start();
            btnGetVerificationCode.setTextColor(Color.parseColor("#A9A9A9"));
            btnGetVerificationCode.setEnabled(false);
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
            ToastUtils.custom(message);
        }

        @Override
        public void onError() {
            super.onError();
        }
    };

    /**
     * 获取图片验证码
     */
    private void getCapCode() {
        LKUtil.getHttpManager().get(HttpConstant.GET_CAP_CODE, getCapCodeHandler);
    }

    /**
     * 获取图片验证码网络请求
     */
    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<GetCapCodeBean> getCapCodeHandler = new BaseHttpAsycResponceHandler<GetCapCodeBean>() {

        @Override
        public void onSuccess(GetCapCodeBean data) {
            super.onSuccess(data);
            if (data != null) {
                capCodeData = data;
                Bitmap bitmap = setImageResourse(data.getImage());
                ivCapCode.setImageBitmap(bitmap);
            } else {
                //加载默认图
                ivCapCode.setImageResource(DEFAULT_CAP_CODE);
            }
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
            //加载默认图
            ivCapCode.setImageResource(DEFAULT_CAP_CODE);
        }

        @Override
        public void onError() {
            super.onError();
            //加载默认图
            ivCapCode.setImageResource(DEFAULT_CAP_CODE);
        }
    };

    /**
     * base64图片解码
     *
     * @param bmMsg
     * @return
     */
    public Bitmap setImageResourse(String bmMsg) {
        Bitmap bitmap = null;
        try {
            byte[] input = ImgHelper.decode(bmMsg);
            bitmap = ImgHelper.bytes2Bimap(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}
